package com.project.nimsen.web.sys;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.project.jdbc.utils.DateUtils;
import com.project.jdbc.utils.Page;
import com.project.jdbc.web.BaseMVCAction;
import com.project.nimsen.dto.AuthDto;
import com.project.nimsen.dto.RoleAuthorDto;
import com.project.nimsen.dto.UserAuthorDto;
import com.project.nimsen.entity.Authority;
import com.project.nimsen.entity.User;
import com.project.nimsen.entity.UserAuthor;
import com.project.nimsen.service.IAuthorityService;
import com.project.nimsen.service.IRoleAuthorService;
import com.project.nimsen.service.IUserAuthorService;
import com.project.nimsen.util.NimsenUtil;
import com.project.nimsen.util.WebUtil;
/**
 * 菜单Control
 * */
@Controller
@RequestMapping(value ="/sys/menu")
public class MenuControl extends BaseMVCAction {
	@Resource
	WebUtil webUtil;
	@Resource
	IAuthorityService authService;
	@Resource
	IRoleAuthorService roleAuthorService;
	@Resource
	IUserAuthorService userAuthorService;
	@RequestMapping(value ="/list")
	public String list(){
		return "/WEB-INF/sys/menu/list";
	}
	/**
	 * 查询方法
	 * */
	@RequestMapping(value="search")
	@ResponseBody
	public Map<String, Object> search(){
		//分页信息
		Page page = new Page(getIntegerParameter("page"));
		page.setPageSize(getIntegerParameter("rows"));
		//返回JSON信息
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("total", 0);
		AuthDto dto = new AuthDto();
		
		try {
			List<Map<String, Object>> rows = authService.findByDto(dto);
			if(CollectionUtils.isEmpty(rows)){
				map.put("rows", "");
				return map;
			}
			//转换时间
			for(Map<String, Object> row : rows){
				Date createTime = (Date)row.get("createTime");
				row.put("createTime", DateUtils.convertDate2String(createTime));
				String entityid = row.get("id").toString();
				row.put("entityid", entityid);
				row.put("id", row.get("number"));
				Object pnumber = row.get("pnumber");
				if(pnumber!=null&&!"0".equals(pnumber.toString()))
					row.put("_parentId", pnumber);
			}
			map.put("rows", rows);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		
		return map;
	}
	/**
	 * 得到用户的权限列表
	 * */
	@RequestMapping(value ="/leftmenu")
	@ResponseBody
	public List<Map<String, Object>> leftmenu(HttpServletRequest request){
		List<Map<String, Object>> list = null;
		User use = webUtil.getCurrUser();
		try {
			list = authService.findAuthorityByUserId(use.getId());
			if(CollectionUtils.isEmpty(list)){
				return null;
			}
			convertZtreeJson(list, null);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return list;
	}
	//转换为zTree的json数据
	private void convertZtreeJson(List<Map<String, Object>> list, List<String> checkeds){
		for(Map<String,Object> map : list){
			map.put("open", "true");
			//表id
			String id = map.get("id").toString();
			map.put("entityid", id);
			Object number = map.get("number");
			map.put("id", number.toString());
			Object pnumber = map.get("pnumber");
			if(pnumber!=null&&StringUtils.isNotBlank(pnumber.toString()))
				map.put("pId", pnumber.toString());
			else
				map.put("pId", "0");
			Object authname = map.get("authname");
			map.put("name", authname.toString());
			Object authurl = map.get("authurl");
			if(authurl!=null&&StringUtils.isNotBlank(authurl.toString())){
//				map.put("hrefurl", webUtil.webUrl(request)+authurl.toString());
				map.put("hrefurl", authurl.toString());
				map.put("target", "_blank");
			}else{
				map.put("hrefurl", "");
				map.put("target", "_blank");
			}
			//判断是否先中节点
			if(CollectionUtils.isEmpty(checkeds))
				continue;
			if(checkeds.contains(id))
				map.put("checked", "true");
		}
	}
	/**
	 * 得到所有的权限列表
	 * */
	@RequestMapping(value ="/leftallmenu")
	@ResponseBody
	public List<Map<String, Object>> leftallmenu(HttpServletRequest request){
		List<Map<String, Object>> list = null;
		//User use = webUtil.getCurrUser();
		String checked = getParameter("checked");
		List<String> checkeds = NimsenUtil.convertStr2List(checked);
		try {
			list = authService.findAllAuthority();
			if(CollectionUtils.isEmpty(list)){
				return null;
			}
			convertZtreeJson(list, checkeds);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return list;
	}
	/**
	 * 向前台返回一个用户权限表的权限id集合以","隔开
	 * */
	@RequestMapping(value ="/beanuseauth")
	@ResponseBody
	public Map<String, Object> beanuseauth(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("success", true);
		
		String id = getParameter("id");
		UserAuthorDto dto = new UserAuthorDto();
		dto.setUseid(id);
		try {
			List<Map<String, Object>> entitys = userAuthorService.findByDto(dto);
			
			if(CollectionUtils.isEmpty(entitys)){
				map.put("authorids", "");
				return map;
			}
			StringBuffer sbf = new StringBuffer();
			for(Map<String, Object> entity : entitys){
				Object objauthorid = entity.get("authorid");
				if(objauthorid==null)
					continue;
				sbf.append(objauthorid.toString()).append(",");
			}
			String authors = sbf.toString();
			map.put("authorids", authors.substring(0, authors.length()-1));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	/**
	 * 保存一系列用记与权限关系的集合
	 * */
	@RequestMapping(value ="/adduseauth")
	@ResponseBody
	public Map<String, Object> adduseauth(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String,Object>();
		User use = webUtil.getCurrUser();
		
		UserAuthorDto dto = new UserAuthorDto();
		dto.setUseid(getParameter("id"));
		dto.setAuthorids(getParameter("authors"));
		dto.setCuruseid(use.getId());
		try {
			if(userAuthorService.saveByDto(dto)){
				map.put("success", true);
				map.put("message", "配置权限成功！");
			}else{
				map.put("success", false);
				map.put("message", "配置权限失败！");
			}
		} catch (Exception e) {
//			map.put("success", false);
//			map.put("message", e.getMessage());
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	/**
	 * 验证权限是否存在
	 * */
	@RequestMapping(value ="/validate")
	@ResponseBody
	public Map<String, Object> validate(){
		Map<String,Object> map = new HashMap<String,Object>();
		
		try {
			AuthDto dto = new AuthDto();
			dto.setPnumber(getParameter("pnumber"));
			dto.setValifield("authname");
			dto.setValivalue(getParameter("authname"));
			dto.setId(getParameter("id"));
			
			StringBuffer sbfMessage = new StringBuffer();
			boolean validate = true;
			Map<String, Object> authnameMap = authService.findVilidate(dto);
			if(authnameMap!=null){
				validate = false;
				sbfMessage.append(" 权限名称");
			}
			
			dto.setValifield("authurl");
			dto.setValivalue(getParameter("authurl"));
			Map<String, Object> authurlMap = authService.findVilidate(dto);
			if(authurlMap!=null){
				validate = false;
				sbfMessage.append(" 访问路径");
			}
			
			if(!validate)
				map.put("message", "在同一级栏目下有"+sbfMessage.toString()+"信息相同!");
			else
				map.put("message", "");
			map.put("success", validate);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	/**
	 * 添加一个权限页面
	 * */
	@RequestMapping(value ="/add")
	public void add(HttpServletRequest request,HttpServletResponse response){
		User use = webUtil.getCurrUser();
		
		String id = getParameter("id");
		String pnumber = getParameter("pnumber");
		Authority child = null;
		try {
			if(StringUtils.isBlank(id)){
				child = new Authority();
				child.setActive(0);
				child.setCreateTime(new Date());
				child.setCreateUser(use.getId());
				child.setNumber(authService.findNextNum(pnumber));
				child.setPnumber(pnumber);
			}else{
				child = authService.findEntityById(id);
			}
			child.setAuthname(getParameter("authname"));
			child.setAuthurl(getParameter("authurl"));
		
			if(StringUtils.isNotBlank(id))
				authService.update(child);
			else
				authService.save(child);
			response.getWriter().println(true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			try {
				response.getWriter().println(false);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	/**
	 * 向前台返回一个实体
	 * */
	@RequestMapping(value ="/bean")
	@ResponseBody
	public Map<String, Object> bean(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String,Object>();
		
		String id = getParameter("id");
		AuthDto dto = new AuthDto();
		dto.setId(id);
		try {
			Map<String, Object> entity = authService.findEntity(dto);
			if(entity==null){
				map.put("success", false);
				map.put("message", " 找不到要操作的栏目！");
				return map;
			}
			map.put("success", true);
			map.put("bean", entity);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	/**
	 * 删除一个权限
	 * */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Map<String, Object> delete(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		AuthDto dto = new AuthDto();
		String id = getParameter("id");
		dto.setId(id);
		try {
			//查询是否还有子栏目
			List<Map<String, Object>> childs = authService.findByDto(dto);
			if(!CollectionUtils.isEmpty(childs)){
				map.put("success", false);
				map.put("message", "此权限下有子权限，请先删除子权限目再进行删除！");
				return map;
			}
			//查询要删除的目录下是否还有文档信息
			authService.deleteByDto(dto);
			map.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	/**
	 * 分配用户所有权限表的接口
	 * UserAuthor
	 * */
	@RequestMapping(value ="/allocationuser")
	public void allocationuser(){
		User use = webUtil.getCurrUser();
		try {
			List<Map<String, Object>> list = authService.findAllAuthority();
			List<UserAuthor> userAuthors = new ArrayList<UserAuthor>();
			for(Map<String, Object> map : list){
				UserAuthor uauthor = new UserAuthor();
				uauthor.setActive(new Integer(0));
				uauthor.setAuthorid(map.get("id").toString());
				uauthor.setCreateTime(new Date());
				uauthor.setCreateUser(use.getId());
				uauthor.setUserid(use.getId());
				userAuthors.add(uauthor);
			}
			if(CollectionUtils.isNotEmpty(authService.save(userAuthors)))
				System.out.println("allocation user_authors success");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
	}
	/**
	 * 跳转到用户权限页面
	 * */
	@RequestMapping(value ="/userlist")
	public String userlist(){
		return "/WEB-INF/sys/menu/userlist";
	}
	
	/****************以下是角色权限信息*****************/
	/**
	 * 跳转到用户权限页面
	 * */
	@RequestMapping(value ="/rolelist")
	public String rolelist(){
		return "/WEB-INF/sys/menu/rolelist";
	}
	/**
	 * 向前台返回一个用户权限表的权限id集合以","隔开
	 * */
	@RequestMapping(value ="/beanroleauth")
	@ResponseBody
	public Map<String, Object> beanroleauth(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("success", true);
		
		String id = getParameter("id");
		RoleAuthorDto dto = new RoleAuthorDto();
		dto.setRoleid(id);
		try {
			List<Map<String, Object>> entitys = roleAuthorService.findByDto(dto);
			
			if(CollectionUtils.isEmpty(entitys)){
				map.put("authorids", "");
				return map;
			}
			StringBuffer sbf = new StringBuffer();
			for(Map<String, Object> entity : entitys){
				Object objauthorid = entity.get("authorid");
				if(objauthorid==null)
					continue;
				sbf.append(objauthorid.toString()).append(",");
			}
			String authors = sbf.toString();
			map.put("authorids", authors.substring(0, authors.length()-1));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	/**
	 * 保存一系列用记与权限关系的集合
	 * */
	@RequestMapping(value ="/addroleauth")
	@ResponseBody
	public Map<String, Object> addroleauth(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String,Object>();
		User use = webUtil.getCurrUser();
		
		RoleAuthorDto dto = new RoleAuthorDto();
		dto.setRoleid(getParameter("id"));
		dto.setAuthorids(getParameter("authors"));
		dto.setCuruseid(use.getId());
		try {
			if(roleAuthorService.saveByDto(dto)){
				map.put("success", true);
				map.put("message", "配置权限成功！");
			}else{
				map.put("success", false);
				map.put("message", "配置权限失败！");
			}
		} catch (Exception e) {
//			map.put("success", false);
//			map.put("message", e.getMessage());
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
}
